<?php

namespace App\Models\OpenShop\InvestmentPromotion;

use App\Enums\OpenShop\InvestmentPromotion\OrganizationManageEnum;
use App\Models\BaseModel;
use App\Models\Traits\KfSoftDeletes;
use App\Service\OpenShop\Feishu\OrganizationManageUserService;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Support\Facades\Cache;

class OpenShopOrganizationManageModel extends BaseModel
{
    use KfSoftDeletes;

    protected $table = 'open_shop_organization_manage';

    protected $appends = [
        'typeText'
    ];

    const TYPE_COMPANY  = 1;  //根据分公司去搜索
    const TYPE_PROVINCE = 2;  //根据具体区域去搜索
    const TYPE_CITY     = 3;  //根据具体区域去搜索

    const HEADQUARTERS_ID   = 1;  //总部ID
    const HEADQUARTERS_TEXT = '全部';  //总部ID

    public function getTypeTextAttribute()
    {
        return OrganizationManageEnum::CODE_TEXT[$this->type] ?? '';
    }

    public function regionRel(): HasMany
    {
        return $this->hasMany(OpenShopOrganizationRegionMappingModel::class, 'manageId');
    }

    public function managerUserRel(): HasMany
    {
        return $this->hasMany(OpenShopOrganizationManageUserModel::class, 'manageId');
    }

    /**
     * 开店组织 缓存 key
     *
     * @param int $userId
     * @return string
     */
    private static function cacheKeyOrganization(int $userId, string $type = "operation"): string
    {
        return sprintf("cacheKeyOrganization:%d:%s", $userId, $type);
    }

    public static function getOrganizationList()
    {
        return self::query()
                   ->where('isDeleted', 0)
                   ->with([
                       'regionRel' => function ($query) {
                           $query->where('isDeleted', 0);
                       }
                   ])
                   ->get();
    }

    /**
     * 根据 用户 ID 获营运数据
     *
     * @param $userId
     * @return mixed
     */
    public static function getOrganizationOperationListByUid($userId)
    {
        return Cache::remember(self::cacheKeyOrganization($userId), getSwitchCacheTime(60), function () use ($userId) {
            $data = self::query()
                        ->where('isDeleted', 0)
                        ->where('operationUid', $userId)
                        ->with([
                            'regionRel' => function ($query) {
                                $query->where('isDeleted', 0);
                            }
                        ])
                        ->get();
            return $data;
        });
    }

    public static function getOrganizationInfoById($manageId)
    {
        return self::query()
                   ->where('id', $manageId)
                   ->with([
                       'regionRel' => function ($query) {
                           $query->where('isDeleted', 0);
                       }
                   ])
                   ->first();
    }

    public static function getManageInfo($manageId)
    {
        return self::query()
                   ->where('id', $manageId)
                   ->first();
    }

    /**
     * 获取省区处理人
     * @param string $provinceCode
     * @param string $cityCode
     * @param int $type
     */
    public function getOrganizationManageId(string $provinceCode, string $cityCode = '', int $type = 0)
    {
        if ($provinceCode && $cityCode && $type) {// 查询区域对应的开发城市经理
            $getManagerInfo = OrganizationManageUserService::getManagerByAddressCodes(
                OpenShopOrganizationManageUserModel::TYPE_DEVELOP_CITY_MANAGER, $provinceCode, $cityCode
            );
            if ($getManagerInfo) {
                return $getManagerInfo['userId'];
            }
        }
        $orgMap = OpenShopOrganizationRegionMappingModel::query()->where('provinceCode', $provinceCode)->first();

        $org = OpenShopOrganizationManageModel::query()->where('id', $orgMap->manageId ?? 1)->first();

        return $org->operationUid;
    }

    /**
     * 根据省份获取组织处理人信息
     *
     * @param string $provinceCode
     * @return Builder|Model|object|null
     */
    public static function getOrganizationManageByProvinceCode(string $provinceCode)
    {
        return OpenShopOrganizationRegionMappingModel::query()
                                                     ->where("provinceCode", $provinceCode)
                                                     ->with("organizationManageRel")
                                                     ->first();
    }


    /**
     * 获取分公司
     * @param array $provinceCodes
     * @return Builder[]|Collection
     */
    public function getBranchByProvinceCode(array $provinceCodes)
    {
        return self::query()
                   ->join('open_shop_organization_region_mapping', 'open_shop_organization_region_mapping.manageId',
                       '=', 'open_shop_organization_manage.id')
                   ->whereIn('open_shop_organization_region_mapping.provinceCode', $provinceCodes)
                   ->where('open_shop_organization_region_mapping.isDeleted', 0)
                   ->groupBy('open_shop_organization_region_mapping.provinceCode')
                   ->select([
                       'open_shop_organization_manage.id',
                       'open_shop_organization_manage.name',
                       'open_shop_organization_region_mapping.provinceCode'
                   ])
                   ->get();
    }

    /**
     * 通过分公司名称获取对应省
     * @param string $branch
     * @return array
     */
    public function getManageIdByBranch(string $branch): array
    {
        $orgMap = self::query()->where('name', $branch)->first();
        return OpenShopOrganizationRegionMappingModel::query()->where('manageId', $orgMap->id ?? 0)->get()->toArray();
    }


    /**
     * 获取所有组织列表
     *
     * @return mixed
     */
    public static function allOrganizationManage(int $cacheTime = 300)
    {
        $allOrganizationManageFunc = function () {
            return self::query()
                       ->where('isDeleted', 0)
                       ->with([
                           'regionRel' => function ($query) {
                               $query->where('isDeleted', 0);
                           },
                           'managerUserRel' => function($query){
                               $query->where('isDeleted', 0);
                           }
                       ])
                       ->get();
        };
        if ($cacheTime > 0) {
            return Cache::remember(vsprintf("%s:%s:%s", [
                __FUNCTION__,
                "all",
                $cacheTime
            ]), getSwitchCacheTime($cacheTime), function () use ($allOrganizationManageFunc) {
                return $allOrganizationManageFunc();
            });
        } else {
            return $allOrganizationManageFunc();
        }
    }
}
